package com.sxkf.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.entity.FriendRecord;
import com.sxkf.template.entity.FriendUser;
import com.sxkf.template.entity.User;
import com.sxkf.template.mapper.FriendRecordMapper;
import com.sxkf.template.mapper.FriendUserMapper;
import com.sxkf.template.mapper.UserMapper;
import com.sxkf.template.service.FriendUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FriendUserServiceImpl extends ServiceImpl<FriendUserMapper, FriendUser> implements FriendUserService{

    @Resource
    private FriendUserMapper friendUserMapper;

    @Resource
    private FriendRecordMapper friendRecordMapper;

    @Resource
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)  // 确保事务管理，发生异常时回滚
    public Boolean agreeFriend(FriendUser friendUser) {
        // 先查找是否有记录存在
        FriendRecord friendRecord = friendRecordMapper.selectOne(new LambdaQueryWrapper<FriendRecord>()
                .eq(FriendRecord::getUserId, friendUser.getFriendId())
                .eq(FriendRecord::getFriendId, friendUser.getUserId()));

        // 判断是否存在记录，若不存在则不进行后续操作
        if (friendRecord == null) {
            log.error("好友记录不存在 for userId: {} and friendId: {}", friendUser.getUserId(), friendUser.getFriendId());
            return false;
        }

        // 更新FriendRecord的状态为"1"
        friendRecord.setStatus("1");
        friendRecordMapper.updateById(friendRecord);

        // 判断FriendUser表中是否已存在这两条记录，避免重复插入
        if (isFriendAlreadyExists(friendUser.getUserId(), friendUser.getFriendId())) {
            log.info("双方好友关系已存在 userId: {} and friendId: {}", friendUser.getUserId(), friendUser.getFriendId());
            return true; // 友情关系已存在，不再插入
        }

        // 向FriendUser表插入双方信息,
        friendUserMapper.insert(friendUser);
        FriendUser friendUser1 = new FriendUser();
        friendUser1.setUserId(friendUser.getFriendId());
        friendUser1.setFriendId(friendUser.getUserId());
        friendUserMapper.insert(friendUser1);

        //双方的好友数+1
        User user = userMapper.selectById(friendUser.getUserId());
        user.setFriendCount(user.getFriendCount() + 1);
        userMapper.updateById(user);

        User friend = userMapper.selectById(friendUser.getFriendId());
        friend.setFriendCount(friend.getFriendCount() + 1);
        userMapper.updateById(friend);

        log.info("成功添加好友关系 userId: {} and friendId: {}", friendUser.getUserId(), friendUser.getFriendId());
        return true;
    }

    // 判断是否已经存在好友关系
    private boolean isFriendAlreadyExists(String userId, String friendId) {
        Long count = friendUserMapper.selectCount(new LambdaQueryWrapper<FriendUser>()
                .eq(FriendUser::getUserId, userId)
                .eq(FriendUser::getFriendId, friendId));
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)  // 确保事务管理，发生异常时回滚
    public Boolean refuseFriend(FriendUser friendUser) {
        // 先查找是否有记录存在
        FriendRecord friendRecord = friendRecordMapper.selectOne(new LambdaQueryWrapper<FriendRecord>()
                .eq(FriendRecord::getUserId, friendUser.getFriendId())
                .eq(FriendRecord::getFriendId, friendUser.getUserId()));

        // 判断是否存在记录，若不存在则不进行后续操作
        if (friendRecord == null) {
            log.error("好友记录不存在 for userId: {} and friendId: {}", friendUser.getUserId(), friendUser.getFriendId());
            return false;
        }else{
            // 更新FriendRecord的状态为"2"
            friendRecord.setStatus("2");
            friendRecordMapper.updateById(friendRecord);
            return true;
        }
    }

    @Override
    public IPage<User> queryFriend(String userId, Integer pageNo, Integer pageSize) {
        // 先查出userId 在好友表中的所有用户ID
        List<String> friendIds = friendUserMapper.selectList(new LambdaQueryWrapper<FriendUser>()
               .eq(FriendUser::getUserId, userId)
               .select(FriendUser::getFriendId))
               .stream()
               .map(FriendUser::getFriendId)
               .collect(Collectors.toList());

        // 再查出好友表中userId 和 friendId 都在friendIds中的所有用户
        IPage<User> page = new Page<>(pageNo, pageSize);

        return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
               .in(User::getId, friendIds));
    }

    @Override
    public IPage<User> queryFriendByName(String userId, String friendName, Integer pageNo, Integer pageSize) {
        // 先查出userId 在好友表中的所有用户ID
        List<String> friendIds = friendUserMapper.selectList(new LambdaQueryWrapper<FriendUser>()
                        .eq(FriendUser::getUserId, userId)
                        .select(FriendUser::getFriendId))
                .stream()
                .map(FriendUser::getFriendId)
                .collect(Collectors.toList());

        // 再查出好友表中userId 和 friendId 都在friendIds中的所有用户
        IPage<User> page = new Page<>(pageNo, pageSize);

        return userMapper.selectPage(page, new LambdaQueryWrapper<User>()
                        .like(User::getNickName,friendName)
                .in(User::getId, friendIds));
    }

    @Override
    @Transactional
    public Boolean deleteFriend(String userId, String friendId) {
        //从好友表中将双方的好友信息删除
        friendUserMapper.delete(new LambdaQueryWrapper<FriendUser>()
               .eq(FriendUser::getUserId, userId)
               .eq(FriendUser::getFriendId, friendId));

        friendUserMapper.delete(new LambdaQueryWrapper<FriendUser>()
               .eq(FriendUser::getUserId, friendId)
               .eq(FriendUser::getFriendId, userId));

        // 好友数-1
        User user = userMapper.selectById(userId);
        user.setFriendCount(user.getFriendCount() - 1);
        userMapper.updateById(user);

        User friend = userMapper.selectById(friendId);
        friend.setFriendCount(friend.getFriendCount() - 1);
        userMapper.updateById(friend);

        return true;
    }
}
